var myApp = angular.module('myApp',['ngRoute']);
myApp.service('contactService',function(){
	this.contacts = [];
	this.add = function(contact){
		this.contacts.push(contact)
	}
	this.getContacts = function() {
		return this.contacts;
	}
	this.getByName = function(name){
		for(i = 0; i < this.contacts.length; i++){
			if(this.contacts[i].name == name)
				return this.contacts[i];
		}
	}
	this.del = function(name){
		for(i = 0; i < this.contacts.length; i++){
			if(this.contacts[i].name == name)
				this.contacts.splice(i,1);
		}
	}
	this.update = function(name,contact) {
		for(i = 0; i < this.contacts.length; i++){
			if(this.contacts[i].name == name){
				this.contacts[i] = contact;
				return true;
			}
		}
	}
});
myApp.config(function($routeProvider){
	$routeProvider
		.when('/',{templateUrl:'list-contact.html',controller:'listCtrl'})
		.when('/add',{templateUrl:'add-new.html',controller:'addCtrl'})
		.when('/edit/:name',{templateUrl:'edit.html',controller:'editCtrl'})
		.otherwise({redirectTo:'/'});
});

myApp.controller('listCtrl',function($scope,$routeParams, contactService){
	$scope.contacts = contactService.getContacts();
	$scope.deleleContact = function(name) {
		return contactService.del(name);
	}
});

myApp.controller('addCtrl',function($scope, $location, contactService){
	$scope.addContact = function(){
		contactService.add($scope.contact);
		$location.path('/')
	}
});
myApp.controller('editCtrl',function($scope, $location, $routeParams,contactService){
	var contact = contactService.getByName($routeParams.name);
	$scope.contact = contact;
	$scope.updateContact = function() {
		contactService.update(contact.name,$scope.contact);
		$location.path('/');
	}
});

